package com.ricervcvcer.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ricervcvcer.common.util.ResultEntity;
import com.ricervcvcer.user.entity.SysRole;
import com.ricervcvcer.user.service.ISysRoleService;
import com.ricervcvcer.user.util.RicervcvcerConstant;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author moge
 * @since 2022-01-10
 */
@RestController
@RequestMapping("sys-role")
public class SysRoleController {
    @Autowired
    ISysRoleService roleService;

    @ApiOperation("查询所有角色")
    @GetMapping("getRoles")
    public ResultEntity<List<SysRole>> getRoles() {
        List<SysRole> list = roleService.list();
        return ResultEntity.successWithData(list);
    }

    @ApiOperation("分页查询角色")
    @PostMapping("page")
    public ResultEntity page(
            @ApiParam("页码") @RequestParam Integer page,
            @ApiParam("每页条数") @RequestParam Integer rows,
            @ApiParam("用户名") @RequestParam String roleName){
        Page<SysRole> list = roleService.page(page,rows,roleName);
        return ResultEntity.successWithData(list);
    }

    @ApiOperation("根据id修改角色访问信息")
    @PostMapping("update")
    public ResultEntity update(
            @ApiParam("角色信息") @RequestBody SysRole sysRole){
        boolean b = roleService.updateById(sysRole);
        if(!b)
            throw new RuntimeException(RicervcvcerConstant.UPDATE_ERROR);
        return ResultEntity.successWithoutData();
    }

    @ApiOperation("根据id查询角色数据")
    @GetMapping("selectById/{id}")
    public ResultEntity selectById(@ApiParam("角色id") @PathVariable Integer id){
        return ResultEntity.successWithData(roleService.getById(id));
    }

    @ApiOperation("添加一个角色")
    @PostMapping("add")
    public ResultEntity add(
            @ApiParam("角色信息") @RequestBody SysRole sysRole){
        QueryWrapper qw=new QueryWrapper();
        qw.eq("role_Name",sysRole.getRoleName());
        SysRole one = roleService.getOne(qw);
        if(!StringUtils.isEmpty(one)){
            throw new RuntimeException("已经存在这个用户！");
        }

        // 设置用户状态、 1 启用
        sysRole.setRoleFlag(1);
        boolean b = roleService.save(sysRole);
        if(!b)
            throw new RuntimeException(RicervcvcerConstant.ADD_ERROR);
        return ResultEntity.successWithoutData();
    }
}
